package com.csproj.system.resource;

import com.codahale.metrics.annotation.Timed;

import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.RoleInfoService;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import com.csproj.system.service.dto.RoleInfoDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing RoleInfo.
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class RoleInfoResource {

    private final Logger log = LoggerFactory.getLogger(RoleInfoResource.class);

    private static final String ENTITY_NAME = "roleInfo";

    private final RoleInfoService roleInfoService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public RoleInfoResource(RoleInfoService roleInfoService,UserInfoService userInfoService,
                            SysLogsService sysLogsService) {
        this.roleInfoService = roleInfoService;
        this.userInfoService = userInfoService;
        this.sysLogsService = sysLogsService;
    }

    /**
     * POST  /roles : 创建角色
     * @param roleInfoDTO 	角色DTO对象
     * @return BaseDTO
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/roleInfos")
    @Timed
    public BaseDTO createRole(@RequestBody RoleInfoDTO roleInfoDTO)  {
        log.debug("REST request to save RoleInfo : {}", roleInfoDTO);
        if (roleInfoDTO.getId() != null) {
            return BaseDTO.createBaseDTO().setSuccess(BaseDTO.CODE_PARAM).setMessage("role_has_exist");
        }
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_role","");
        return roleInfoService.save(roleInfoDTO).setMessage("create_role_success");
    }

    /**
     * PUT  /roles : 修改角色信息.
     * @param roleInfoDTO 	角色DTO对象
     * @param id		角色id
     * @return DTO
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/roleInfos/{id}")
    @Timed
    public BaseDTO updateRole(@RequestBody RoleInfoDTO roleInfoDTO, @PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update Role : {}", roleInfoDTO);
        roleInfoDTO.setId(id);
        if (roleInfoDTO.getId() == null) {
            return createRole(roleInfoDTO);
        }
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":update_role_success","");
        return roleInfoService.save(roleInfoDTO);
    }

    /**
     * GET  /roles : 获取角色信息(分页)
     * @param pageNumber		页数
     * @param keyWord				角色名称
     * @return BaseDTO
     */
    @GetMapping("/roleInfos")
    @Timed
    public BaseDTO getAllRoleInfos(@RequestParam(value="pageNumber",required=false) Integer pageNumber,
                                   @RequestParam(value="pageSize",required = false) Integer pageSize,
                                   @RequestParam(value="keyWord",required=false) String keyWord) {
        log.debug("REST request to get all RoleInfos");
        Pageable pageable = PageableTools.basicPage(pageNumber,pageSize);
        String hsql = "";
		Map<String, Object> queryParams = new HashMap<String, Object>();
    	if (StringUtils.isNotBlank(keyWord)) {
			hsql += " and r.name like :name ";
			queryParams.put("name", "%"+keyWord+"%");
		}

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_get_role_list","");
        return roleInfoService.findPageList(hsql,queryParams,pageable);
    }

    /**
     * GET  /roles : 获取角色信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allRoleInfos")
    @Timed
    public BaseDTO getAllRoleInfos() {
       return BaseDTO.createBaseDTOByFieldList(roleInfoService.findAll());
    }

    /**
     * GET 获取角色信息
     * @param id 	角色id
     * @return BaseDTO
     */
    @GetMapping("/roleInfos/{id}")
    @Timed
    public BaseDTO getRole(@PathVariable String id) {
        log.debug("REST request to get Role : {}", id);
        RoleInfoDTO roleInfoDTO = roleInfoService.findOne(id);
        return BaseDTO.createBaseDTO(roleInfoDTO);
    }

    /**
     * DELETE  /roles/:id : 删除角色信息
     * @param 	id 		角色id
     * @return 	BaseDTO
     */
    @DeleteMapping("/roleInfos/{id}")
    @Timed
    public BaseDTO deleteRole(@PathVariable String id) {
        log.debug("REST request to delete Role : {}", id);
        roleInfoService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 根据角色id 授权
     */
    @PutMapping("/roleInfos/{id}/authorize")
    @Timed
    public BaseDTO authorize(@PathVariable String id,@RequestBody List<String> ids){
        roleInfoService.authorizeById(id,ids);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_set_authorize_list","");
        return BaseDTO.createBaseDTO();
    }

    /**
     * PUT  /roleInfos/updateRoleInfoStatus/{id} : 修改角色使用状态
     *
     * @param roleInfoDTO
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/roleInfos/updateRoleInfoStatus/{id}")
    @Timed
    public BaseDTO updateRoleInfoStatus(HttpServletRequest request, @RequestBody(required = false) RoleInfoDTO roleInfoDTO, @PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", roleInfoDTO);
        roleInfoDTO.setId(id);

        RoleInfoDTO result = roleInfoService.updateRoleInfoStatus(roleInfoDTO);


        return BaseDTO.createBaseDTO(result).setMessage("change_role_state_success");
    }
}
